import re

from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from django.conf import settings
from users.models import User
from rest_framework_jwt.settings import api_settings


class RegisterCreateUserSerializer(ModelSerializer):


    #用户再进行提交的时候有3个数据:校验密码,短信验证码,是否同意协议
    #所以,我们需要定义三个字段
    password2 = serializers.CharField(label='校验密码',allow_null=False,allow_blank=False,write_only=True)
    sms_code = serializers.CharField(label='短信验证码',max_length=6,min_length=6,allow_null=False,allow_blank=False,write_only=True)
    allow = serializers.CharField(label='是否同意协议',allow_null=False,allow_blank=False,write_only=True)

    token = serializers.CharField(label='序列化时返回给前端的token', read_only=True)
    class Meta:
        model = User
        fields = ('id','username','password','mobile','password2','sms_code','allow', 'token')
        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    #进行校验
    #单个字段的校验有 手机号码,是否同意协议
    def validate_mobile(self, value):

        if not re.match(r'1[3-9]\d{9}', value):
            raise serializers.ValidationError('手机号格式不正确')

        return value

    def validate_allow(self, value):

        if value != 'true':
            raise serializers.ValidationError('您未同意协议')

        # return value

        return value

    #多字段校验, 密码是否一致, 短信是否一致
    def validate(self, attrs):

        password = attrs['password']
        password2 = attrs['password2']

        if password != password2:
            raise serializers.ValidationError('密码不一致')

        # 比较手机验证码
        # 1.获取用户提交的验证码
        code = attrs['sms_code']

        # 2.取出redis中的验证码
        redis_conn = get_redis_connection('code')

        # 3.获取手机号码
        mobile = attrs['mobile']
        redis_code = redis_conn.get('sms_%s' % mobile)

        if redis_code is None:
            raise serializers.ValidationError('验证码已过期')

        if redis_code.decode() != code:
            raise serializers.ValidationError('验证码不正确')

        return attrs

    def create(self, validated_data):

        # 删除多余字段
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = super().create(validated_data)

        # 修改密码
        user.set_password(validated_data['password'])
        user.save()


        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        self.token = token

        return user


# 用户详情信息序列化器
class UserDetailSerializer(serializers.ModelSerializer):

    class Meta:

        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class EmailUpdateSerializer(serializers.ModelSerializer):

    class Meta:

        model = User
        fields = ['id', 'email']

        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    # 重写update方法，对邮件信息进行更新操作
    def update(self, instance, validated_data):

        email = validated_data.get('email')
        instance.email = email
        instance.save()

        # 我们在这里发送邮件
        from django.core.mail import send_mail

        # subject, message, from_email, recipient_list,html_message=None
        # subject: 主题
        subject = '美多商城激活邮件<selery>'
        # message,  内容,普通内容
        message = 'aaa'
        # from_email,  谁发送的
        from_email = '美多商城<qi_rui_hua@163.com>'
        # recipient_list: 谁接收 []
        recipient_list = [email]
        # html_message  , 丰富的邮件内容可以传递 html
        # html_message = '<h1>lalala</h1>'

        # 生成一个 对id和email进行处理的一个url
        verify_url = instance.generice_active_url()

        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)

        # send_mail(subject,
        #           message,
        #           from_email,
        #           recipient_list,
        #           html_message=html_message)

        from celery_tasks.email.tasks import send_verify_email

        send_verify_email.delay(subject,
                                message,
                                from_email,
                                recipient_list,
                                html_message=html_message)

        return instance
